﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Jhong.FunMVC.Razor
{
    using System.ComponentModel;

    public class DynamicViewDataDictionary : DynamicObject
    {
        private readonly Func<ViewDataDictionory> _viewDataThunk;

        private readonly Func<object> _model;

        private readonly PropertyDescriptorCollection _modelDewscription;

        internal readonly static string InnerViewDataReplaceStr = "_FunRZVM";

        private ViewDataDictionory ViewData
        {
            get
            {
                return this._viewDataThunk();
            }
        }

        private object Model
        {
            get
            {
                return this._model();
            }
        }

        private object GetModel(string key)
        {
            for (int i = 0; i < this._modelDewscription.Count; i++)
            {
                var curr = this._modelDewscription[i];
                if (false == curr.Name.Equals(key)) continue;
                return curr.GetValue(this.Model);
            }
            return null;
        }


        public DynamicViewDataDictionary(Func<ViewDataDictionory> viewDataThunk, Func<object> modelDataThunk)
        {
            this._viewDataThunk = viewDataThunk;
            this._model = modelDataThunk;
            this._modelDewscription = TypeDescriptor.GetProperties(modelDataThunk());
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return this.ViewData.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (binder.Name.Equals(InnerViewDataReplaceStr))
            {
                result = this.ViewData;
                return true;
            }
            result = this.GetModel(binder.Name);
            return true;
        }
    }
}
